package com.ruoyi.system.domain;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

public class VerificationExportUtil {

    /**
     * 按培训分组导出核销数据到Excel
     *
     * @param response HTTP响应
     * @param groupedData 按培训分组的数据
     * @param fileName 文件名
     * @throws IOException IO异常
     */
    public static void exportGroupedExcel(HttpServletResponse response,
                                          Map<String, List<VerificationExportVO>> groupedData,
                                          String fileName) throws IOException {
        System.out.println("开始生成Excel文件，数据量：" + groupedData.size());
        Workbook workbook = new XSSFWorkbook();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        // 为每个培训创建一个工作表
        for (Map.Entry<String, List<VerificationExportVO>> entry : groupedData.entrySet()) {
            String trainingName = entry.getKey();
            List<VerificationExportVO> dataList = entry.getValue();
            System.out.println("处理培训: " + trainingName + "，数据条数：" + dataList.size());

            // 创建工作表（限制工作表名称长度）
            String sheetName = trainingName.length() > 31 ? trainingName.substring(0, 31) : trainingName;
            Sheet sheet = workbook.createSheet(sheetName);

            // 创建表头
            createHeaderRow(sheet, dataList.isEmpty() ? null : dataList.get(0));

            // 填充数据
            fillDataRows(sheet, dataList, dateFormat);
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" +
                java.net.URLEncoder.encode(fileName, "UTF-8") + "\"");

        // 写入响应流
        OutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();
        out.close();
        workbook.close();
        System.out.println("Excel文件生成完成");
    }

    /**
     * 创建表头行
     */
    private static void createHeaderRow(Sheet sheet, VerificationExportVO sampleData) {
        Row headerRow = sheet.createRow(0);

        // 固定列头
        String[] fixedHeaders = {"序号", "培训名称", "培训时间", "姓名", "员工编号", "性别", "部门", "电话", "邮箱"};
        for (int i = 0; i < fixedHeaders.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(fixedHeaders[i]);
            cell.setCellStyle(createHeaderCellStyle(sheet.getWorkbook()));
        }

        // 动态列头（根据培训期间的日期生成）
        if (sampleData != null && sampleData.getStartDate() != null && sampleData.getEndDate() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(sampleData.getStartDate());

            int colIndex = fixedHeaders.length;
            while (!cal.getTime().after(sampleData.getEndDate())) {
                Date currentDate = cal.getTime();
                String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(currentDate);

                // 午餐列
                Cell lunchCell = headerRow.createCell(colIndex++);
                lunchCell.setCellValue(dateStr + " 午餐");
                lunchCell.setCellStyle(createHeaderCellStyle(sheet.getWorkbook()));

                // 晚餐列
                Cell dinnerCell = headerRow.createCell(colIndex++);
                dinnerCell.setCellValue(dateStr + " 晚餐");
                dinnerCell.setCellStyle(createHeaderCellStyle(sheet.getWorkbook()));

                // 移动到下一天
                cal.add(Calendar.DAY_OF_MONTH, 1);
            }
        } else {
            // 如果没有日期范围，至少添加一些示例列以避免Excel文件格式错误
            Cell lunchCell = headerRow.createCell(fixedHeaders.length);
            lunchCell.setCellValue("日期 午餐");
            lunchCell.setCellStyle(createHeaderCellStyle(sheet.getWorkbook()));

            Cell dinnerCell = headerRow.createCell(fixedHeaders.length + 1);
            dinnerCell.setCellValue("日期 晚餐");
            dinnerCell.setCellStyle(createHeaderCellStyle(sheet.getWorkbook()));
        }
    }
    /**
     * 填充数据行
     */
    private static void fillDataRows(Sheet sheet, List<VerificationExportVO> dataList, SimpleDateFormat dateFormat) {
        int rowNum = 1;
        for (VerificationExportVO data : dataList) {
            Row row = sheet.createRow(rowNum++);

            // 填充固定列数据
            row.createCell(0).setCellValue(data.getSeq() != null ? data.getSeq() : rowNum - 1);
            row.createCell(1).setCellValue(data.getTrainingName() != null ? data.getTrainingName() : "");
            row.createCell(2).setCellValue(data.getTrainingTime() != null ? data.getTrainingTime() : "");
            row.createCell(3).setCellValue(data.getEmployeeName() != null ? data.getEmployeeName() : "");
            row.createCell(4).setCellValue(data.getEmployeeNo() != null ? data.getEmployeeNo() : "");
            row.createCell(5).setCellValue(data.getSex() != null ? data.getSex() : "");
            row.createCell(6).setCellValue(data.getDept() != null ? data.getDept() : "");
            row.createCell(7).setCellValue(data.getPhone() != null ? data.getPhone() : "");
            row.createCell(8).setCellValue(data.getEmail() != null ? data.getEmail() : "");

            // 填充动态列数据（核销信息）
// 填充动态列数据（核销信息）
            if (data.getStartDate() != null && data.getEndDate() != null && data.getDailyVerifications() != null) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(data.getStartDate());

                int colIndex = 9; // 从第10列开始填入动态数据
                while (!cal.getTime().after(data.getEndDate())) {
                    Date currentDate = cal.getTime();
                    String dateStr = dateFormat.format(currentDate);

                    // 获取该日期的核销信息
                    Map<String, String> mealInfo = data.getDailyVerifications().get(dateStr);
                    if (mealInfo == null) {
                        mealInfo = new HashMap<>();
                    }

                    // 午餐核销状态
                    String lunchStatus = mealInfo.getOrDefault("午餐", "");
                    row.createCell(colIndex++).setCellValue(lunchStatus);

                    // 晚餐核销状态
                    String dinnerStatus = mealInfo.getOrDefault("晚餐", "");
                    row.createCell(colIndex++).setCellValue(dinnerStatus);

                    // 移动到下一天
                    cal.add(Calendar.DAY_OF_MONTH, 1);
                }
            } else {
                // 如果没有日期范围，至少填充一些默认值以避免Excel格式错误
                row.createCell(9).setCellValue("");
                row.createCell(10).setCellValue("");
            }
        }

        // 自动调整列宽
        for (int i = 0; i < sheet.getRow(0).getLastCellNum(); i++) {
            sheet.autoSizeColumn(i);
        }
    }

    /**
     * 创建表头单元格样式
     */
    private static CellStyle createHeaderCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        return style;
    }
}